﻿using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assets.Client.RunTime.Manager
{
    /// <summary>
    /// 消息发布管理器
    /// </summary>
    public class MessagePublisher
    {
        private static MessagePublisher single;

        private static Dictionary<Messages.IMessage.Types.MessageType, 
            Action<Messages.IMessage>> listeners = 
            new Dictionary<Messages.IMessage.Types.MessageType, Action<Messages.IMessage>>(); 

        public static MessagePublisher Single
        {
            get
            {
                if (single == null)
                {
                    single = new MessagePublisher();
                }
                return single;
            }
        }

        /// <summary>
        /// 订阅者订阅
        /// </summary>
        public void Subscribe(Messages.IMessage.Types.MessageType type, Action<Messages.IMessage> method)
        {
            if (listeners.TryGetValue(type, out Action<Messages.IMessage> evt))
            {
                evt += method;
            } else
            {
                listeners[type] = method;
            }
        }

        /// <summary>
        /// 订阅者取消订阅
        /// </summary>
        public void Unsubscribe(Messages.IMessage.Types.MessageType type, Action<Messages.IMessage> method)
        {
            if (listeners.TryGetValue(type, out Action<Messages.IMessage> evt))
            {
                evt -= method;
            }
        }

        /// <summary>
        /// 发布信息
        /// </summary>
        public void NotifyMessage(Messages.IMessage iMessage)
        {
            Messages.IMessage.Types.MessageType type = iMessage.MessageType;
            if (listeners.TryGetValue(type, out Action<Messages.IMessage> evt))
            {
                evt.Invoke(iMessage);
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        public void SendMessage(Messages.IMessage iMessage, ProtocolType type)
        {

        }
    }

    /// <summary>
    /// 网络协议类型
    /// </summary>
    public enum ProtocolType
    {
        TCP, UDP
    }
}
